<template>
  <div class="blog-admin-container">
    <el-card>
      <div class="blog-admin-container-title">{{ $route.meta.title }} </div>

      <div class="add-articles-btn-group">
        <el-input
          v-model="articlesData.articles_title"
          placeholder="文章标题"
          clearable
          size="medium"
        />
        <el-button v-show="draftIsShow" size="medium" type="primary" @click="openDraft">草稿箱</el-button>
        <el-tooltip v-show="draftIsShow" class="item" effect="dark" :content="title_content_check[1]" placement="top">
          <span><el-button size="medium" :disabled="title_content_check[0] || isDisabled" @click="createDraft">保存草稿</el-button></span>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="title_content_check[1]" placement="top">
          <span><el-button size="medium" type="danger" :disabled="title_content_check[0]" @click="saveReleaseArticles">{{ $route.meta.title }}</el-button></span>
        </el-tooltip>

      </div>
      <div class="add-articles-md">
        <mavon-editor ref="md" v-model="articlesData.articles_content" style="height: 100%" :ishljs="true" @imgAdd="handleEditorImgAdd" />
      </div>

      <el-dialog
        :title="$route.meta.title"
        :visible.sync="dialogData.dialogVisible"
        width="30%"
        top="5vh"
        @close="dialogData.dialogVisible = false"
      >
        <div class="article-add-info">
          <div>
            <span class="articles-add-title">文章分类</span>
            <el-popover
              v-if="articlesData.categorie === ''"
              placement="bottom-start"
              trigger="click"
              width="500"
            >
              <div class="popover-box">
                <div v-if="categoriesList.total !== 0" class="categorie-list">
                  <div v-for="categorie in categoriesList.data" :key="categorie.id" @click="addCategorie(categorie)">{{ categorie.categorie_name }}</div>
                  <el-pagination
                    small
                    layout="prev, pager, next"
                    :hide-on-single-page="true"
                    :page-size="categoriesList.pageSize"
                    :total="categoriesList.total"
                    @current-change="categoriesChange"
                  />
                </div>
                <div v-else>
                  暂无任何分类，请先创建分类
                </div>
              </div>
              <el-button slot="reference" class="add-categories" size="medium">添加分类</el-button>
            </el-popover>
            <el-tag
              v-else
              closable
              :disable-transitions="false"
              @close="delCategorie"
            >{{ articlesData.categorie.categorie_name }}</el-tag>
          </div>
          <div>
            <span class="articles-add-title">文章标签</span>

            <el-tag
              v-for="(tag,index) in articlesData.tags"
              :key="index"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag.tag_name }}
            </el-tag>
            <el-popover
              v-if="!(articlesData.tags.length === 3)"
              placement="bottom-start"
              trigger="click"
              width="600"
            >
              <div class="popover-box">
                <div style="margin: 20px 0">添加标签</div>
                <div v-if="tagsList.total !==0">
                  <el-button v-for="tag in tagsList.data" :key="tag.id" size="small" :disabled="articlesData.tags.findIndex(item =>{return item.id === tag.id}) !== -1" class="tags add-tags" @click="addTags(tag,$event)">{{ tag.tag_name }}</el-button>
                  <el-pagination
                    small
                    layout="prev, pager, next"
                    :page-size="tagsList.pageSize"
                    :total="tagsList.total"
                    :hide-on-single-page="true"
                    @current-change="tagChange"
                  />
                </div>
                <div v-else>
                  暂无任何标签，请先创建标签
                </div>
              </div>

              <el-button slot="reference" size="medium" class="add-tags">添加标签</el-button>
            </el-popover>
          </div>
          <div>
            <span class="articles-add-title">文章类型</span>
            <el-select v-model="articlesData.articles_type" placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>

          <div v-show="articlesData.articles_type != '0'">
            <span class="articles-add-title">原文链接</span>
            <el-input v-model="articlesData.articles_reprint_url" style="width: 80%" />
          </div>

          <el-switch
            v-model="dialogData.linkPerhapsFileUpload"
            active-color="#13ce66"
            inactive-color="#409eff"
            active-text="图片链接"
            inactive-text="文件上传"
          />
          <div>
            <span class="articles-add-title">文章封面</span>
            <div class="upload-images">
              <el-upload
                v-if="dialogData.linkPerhapsFileUpload === false"
                drag
                multiple
                action="null"
                :http-request="imageUpload"
              >
                <div v-if="!articlesData.articles_image_url">
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </div>
                <el-image
                  v-else
                  style="width: 100%; height: 100%"
                  :src="articlesData.articles_image_url"
                  fit="cover"
                />
              </el-upload>
              <el-input v-else v-model="articlesData.articles_image_url" class="upload-images-link" />
            </div>
          </div>
          <div>
            <span class="articles-add-title">是否置顶</span>
            <el-switch
              v-model="articlesData.articles_is_topping"
              :active-value="1"
              :inactive-value="0"
            />
          </div>
          <div>
            <span class="articles-add-title">发布类型</span>
            <el-radio v-model="articlesData.articles_status" :label="0">公开</el-radio>
            <el-radio v-model="articlesData.articles_status" :label="2">隐藏</el-radio>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogData.dialogVisible = false">取 消</el-button>
          <el-tooltip class="item" effect="dark" :content="post_check[1]" placement="top">
            <span style="display: inline-block;margin-left: 10px"><el-button type="primary" :disabled="post_check[0] || isDisabled" @click="createArticlesbtn">确 定</el-button></span>
          </el-tooltip>
        </span>
      </el-dialog>

      <el-dialog
        title="草稿箱"
        :visible.sync="draftDialog.dialogVisible"
        width="50%"
        @close="draftDialog.dialogVisible = false"
      >
        <div class="draft-search-container">
          <el-input
            v-model="draftDialog.search"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="搜索草稿名称"
            clearable
            @clear="clearSearch"
          />
          <el-button type="primary" size="small" icon="el-icon-search" :disabled=" draftDialog.search.length === 0" @click="getDraftListInfo()">搜索</el-button>
        </div>
        <el-table
          :data="draftDialog.draftData"
          style="width: 100%"
        >
          <el-table-column
            align="center"
            prop="draft_title"
            label="标题"
          />
          <el-table-column
            align="center"
            prop="create_time"
            label="保存时间"
          />
          <el-table-column
            align="center"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button :disabled="draftDialog.current_draft_id === scope.row.id" style="margin-right: 5px" size="mini" icon="el-icon-edit" type="primary" @click="clickEdit(scope.row.id)">编辑</el-button>
              <el-popconfirm
                confirm-button-text="我确定"
                cancel-button-text="点错了"
                title="这个草稿确定删除？"
                @onConfirm="deleteDraft(scope.row.id)"
              >
                <el-button slot="reference" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>
        <div class="draft-pagination"> <el-pagination
          small
          :page-size="draftDialog.pageSize"
          layout="prev, pager, next"
          :total="draftDialog.total"
          @current-change="draftChange"
        /></div>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import { getTags } from '@/api/tags'
import { getCategories } from '@/api/categories'
import { Message } from 'element-ui'
import { uploadOSS, uploadToken } from '@/api/user'
import { checkURL } from '@/utils/index'
import { createArticlesApi, createDraftApi, updateDraftApi, getDraftListApi, deleteDraftApi, getArticlesApi, getDraftInfoApi } from '@/api/articles'
import { updateArticleApi } from '@/api/articleslist'

export default {
  name: 'AddArticles',
  data() {
    return {
      dialogData: {
        dialogVisible: false,
        linkPerhapsFileUpload: true
      },
      draftDialog: {
        current_draft_id: '',
        dialogVisible: false,
        total: 0,
        pageNum: 1,
        pageSize: 4,
        search: '',
        draftData: []
      },
      categoriesList: {
        total: 0,
        data: [],
        pageNum: 1,
        pageSize: 4
      },
      tagsList: {
        total: 0,
        data: [],
        pageNum: 1,
        pageSize: 12
      },
      typeList: [
        {
          id: '0',
          name: '原创'
        },
        {
          id: '1',
          name: '转载'
        }, {
          id: '2',
          name: '翻译'
        }
      ],
      articlesData: {
        articles_title: '',
        articles_content: '',
        categorie: '',
        tags: [],
        articles_image_url: '',
        articles_status: 0,
        articles_type: '0',
        articles_reprint_url: '',
        articles_is_topping: '0'
      },
      update_article_id: '',
      isDisabled: false
    }
  },
  computed: {
    // 检查是否完成标题和内容的填写
    title_content_check() {
      if (this.articlesData.articles_title.length <= 0) {
        return [true, '文章标题为空']
      }
      if (this.articlesData.articles_content.length <= 0) {
        return [true, '文章内容为空']
      }
      return [false, '创建文章']
    },
    // 发布文章检查
    post_check() {
      // 分类为空
      if (this.articlesData.categorie === '') {
        return [true, '文章分类为空']
      }
      // 标签为空
      if (this.articlesData.tags.length === 0) {
        return [true, '文章标签为空']
      }

      // 如果 文章不是原创,必须存在原创链接
      if (this.articlesData.articles_type !== '0') {
        if (!checkURL(this.articlesData.articles_reprint_url)) {
          return [true, '文章转载/翻译链接必须填写']
        }
      }

      // 文章图片为空
      if (!checkURL(this.articlesData.articles_image_url)) {
        return [true, '文章图片为空']
      }

      return [false, '创建文章']
    },
    // 草稿是否显示
    draftIsShow() {
      return this.$route.name !== 'update_article'
    }
  },
  created() {
    this.getTagsInfo(this.tagsList.pageNum)
    this.getCategoriesInfo(this.categoriesList.pageNum)
    // 如果是 编辑草稿
    if (this.$route.name === 'edit_article') {
      this.getEditInfo()
    } else if (this.$route.name === 'update_article') { // 如果是更新文章
      this.getUpdateInfo()
    }
  },
  methods: {
    getTagsInfo(pageNum) {
      getTags({ article: 'article', pageNum: pageNum, pageSize: this.tagsList.pageSize }).then(resp => {
        this.tagsList.data = resp.data.result
        this.tagsList.total = resp.data.total
      })
    },
    getCategoriesInfo(pageNum) {
      getCategories({ article: 'article', pageNum: pageNum, pageSize: this.categoriesList.pageSize }).then(resp => {
        this.categoriesList.data = resp.data.result
        this.categoriesList.total = resp.data.total
      })
    },
    getDraftListInfo(pageNum = 1) {
      const params = {
        pageNum: pageNum,
        pageSize: this.draftDialog.pageSize
      }
      if (this.draftDialog.search.length > 0) {
        params.search = this.draftDialog.search
      }
      getDraftListApi(params).then(resp => {
        this.draftDialog.draftData = resp.data.result
        this.draftDialog.total = resp.data.total
      })
    },
    deleteDraft(id) {
      deleteDraftApi({ id: id }).then(resp => {
        Message({
          message: '删除成功',
          type: 'success',
          duration: 5 * 1000
        })
        this.getDraftListInfo()
      })
    },
    clearSearch() {
      this.draftDialog.search = ''
      this.getDraftListInfo()
    },
    draftChange(currentPage) {
      this.draftDialog.pageNum = currentPage
      this.getDraftListInfo(this.draftDialog.pageNum)
    },
    categoriesChange(currentPage) {
      this.categoriesList.pageNum = currentPage
      this.getCategoriesInfo(currentPage)
    },
    tagChange(currentPage) {
      this.tagsList.pageNum = currentPage
      this.getTagsInfo(currentPage)
    },
    saveReleaseArticles() {
      if (this.articlesData.articles_content === '') {
        this.$message.error('文章内容为空~~~')
        return
      }
      if (this.articlesData.articles_title === '') {
        this.$message.error('文章标题为空~~~')
        return
      }
      this.dialogData.dialogVisible = true
    },
    addCategorie(cateogire) {
      this.articlesData.categorie = cateogire
    },
    delCategorie() {
      this.articlesData.categorie = ''
    },
    addTags(tag, tagEvent) {
      if (this.articlesData.tags.indexOf(tag) === -1) {
        this.articlesData.tags.push(tag)
      }
    },
    handleClose(tag) {
      this.articlesData.tags.splice(this.articlesData.tags.indexOf(tag), 1)
    },
    imageUpload(file) {
      const this_ = this
      uploadToken('image').then(resp => {
        uploadOSS(resp.data.token, file.file).then(resp => {
          Message({
            message: '上传成功!',
            type: 'success',
            duration: 5 * 1000
          })
          this_.articlesData.articles_image_url = resp.config.url.split('?')[0]
        })
      })
    },
    // md上传图片
    handleEditorImgAdd(pos, $file) {
      uploadToken('image').then(resp => {
        uploadOSS(resp.data.token, $file).then(resp => {
          Message({
            message: '上传成功!',
            type: 'success',
            duration: 5 * 1000
          })
          this.$refs.md.$img2Url(pos, resp.config.url.split('?')[0])
        })
      })
    },
    // 创建文章
    createArticlesbtn() {
      // 组装数据
      this.isDisabled = true // 防止再次点击创建
      const data = JSON.parse(JSON.stringify(this.articlesData))
      data.categorie = this.articlesData.categorie.id
      data.tags = this.articlesData.tags.map(item => { return item.id })
      if (this.draftDialog.current_draft_id !== '') {
        data.draft_id = this.draftDialog.current_draft_id
      }
      var useArticlesApi = createArticlesApi
      var message = '创建文章成功'
      if (this.$route.name === 'update_article' && this.update_article_id.length !== 0) {
        useArticlesApi = updateArticleApi
        data.id = this.update_article_id
        message = '更新文章成功'
      }
      useArticlesApi(data).then(resp => {
        Message({
          message: message,
          type: 'success',
          duration: 5 * 1000
        })
        const this_ = this
        setTimeout(function() {
          this_.$store.dispatch('tagsView/delAllViews')
          this_.$router.replace('/articles/list')
        }, 1000)
      }).catch(e => {
        this.isDisabled = false
      })
    },
    openDraft() {
      this.getDraftListInfo()
      this.draftDialog.dialogVisible = true
    },
    createDraft() {
      this.isDisabled = true
      const params = { draft_title: this.articlesData.articles_title,
        draft_data: this.articlesData.articles_content
      }
      if (this.draftDialog.current_draft_id !== '') {
        params.id = this.draftDialog.current_draft_id
      }
      let useDraftApi = createDraftApi
      // 根据路由使用不同的api进行保存
      if (this.$route.name === 'edit_article') {
        useDraftApi = updateDraftApi
      }
      useDraftApi(params).then(resp => {
        Message({
          message: '草稿保存成功',
          type: 'success',
          duration: 5 * 1000
        })
        this.isDisabled = false
        this.draftDialog.current_draft_id = resp.data.id
      }).catch(e => {
        this.isDisabled = false
      })
    },
    getEditInfo() {
      // 编辑草稿获取数据
      if (this.$route.query.id !== undefined) {
        getDraftInfoApi({ id: this.$route.query.id }).then(resp => {
          this.draftDialog.current_draft_id = resp.data.id
          this.articlesData.articles_title = resp.data.draft_title
          this.articlesData.articles_content = resp.data.draft_data
        })
      }
    },
    clickEdit(id) {
      // 编辑文章跳转
      this.$router.push('/articles/edit?id=' + id)
      if (this.$route.name === 'edit_article') {
        location.reload()
      }
    },
    getUpdateInfo() {
      // 获取更新文章数据
      if (this.$route.query.id !== undefined) {
        getArticlesApi({ id: this.$route.query.id }).then(resp => {
          const data = resp.data
          this.update_article_id = data.id
          delete data.id
          this.articlesData = data
          this.articlesData.articles_type = String(this.articlesData.articles_type)
          // this.typeList.find(item => item.id === String(this.articlesData.articles_type))
        })
      }
    }
  }
}
</script>

<style lang="less">

  .add-articles-btn-group {
    display: flex;
    justify-content: right;

    .el-button {
      margin-left: 20px;
    }

  }

  .add-articles-md {
    margin-top: 21px;
    height: calc(100vh - 280px);
  }
  .add-tags {
    color: #409eff;
    border-color: #409eff;
    background-color: #ecf5ff;
  }

  .article-add-info {
    padding: 20px;

    & >div {
      margin-bottom: 30px;
    }

    & >div >span {
      margin-right: 30px;
    }

    .add-categories {
      color: #67c23a;
      border-color: #67c23a;
      background-color: #f0f9eb;
    }

    .add-categories:hover {
      background-color: #67c23a;
      color: #ffffff;
    }

    .add-tags:hover {
      background-color: #409eff;
      color: #ffffff;
    }

  }

  .popover-box {
    margin: 20px;

    .categorie-list {
      padding-top: 10px;
      & > div {
        font-size: 1rem;
        padding: 10px;
      }

      & > div:hover {
        color: #67c23a;
        background-color: #f0f9eb;
      }
    }

    .tags{
      margin-bottom: 15px;
      margin-left: 20px;
    }

  }
  .upload-images {
    display: inline-block!important;
    width: 80%;
    vertical-align: middle;

    .upload-images-link {
    }
  }

  .draft-search-container {
    display: flex;

    & div:first-child {
      margin-right: 20px;
    }

  }

  .draft-pagination{
    display: flex;
    justify-content: center;
    padding-top: 20px;
  }

</style>
